const {
	Service
} = require('uni-cloud-router')
const config = require('../config-uni-id-merchant.js')
const WXBizDataCrypt = require('../WXBizDataCrypt.js')
const uniID = require('uni-id')

const getUniID = (context) => {
	return uniID.createInstance({
		context,
		config
	})
}

const dbHelper = require('db-helper')

module.exports = class MerchantService extends Service {
	
	async bindWX({
		code,
		wxUserInfo
	}) {
		let user = await dbHelper.getById("uni-id-users", this.ctx.auth.uid)
		let merchantInfo = user.merchant_info
		if (merchantInfo && merchantInfo.wx_openid && merchantInfo.wx_openid["mp-weixin"]) {
			throw new Error("请先解绑微信，然后再绑定")
		}
		const res = await getUniID(this.ctx.context).code2SessionWeixin({
			code
		})
		if (res.code) {
			throw new Error(res.message)
		}
		let pc = new WXBizDataCrypt(config['mp-weixin'].oauth.weixin.appid, res.sessionKey)
		let info = pc.decryptData(wxUserInfo.encryptedData , wxUserInfo.iv)
		console.log("解密之后的微信用户数据", info)
		let data = {
			_id: user._id,
			nickname: info.nickName,
			avatar: info.avatarUrl,
			gender: info.gender,
			merchant_info: {
				wx_unionid: res.unionid,
				wx_openid: {
					"mp-weixin": res.openid
				}
			}
		}
		await dbHelper.update("uni-id-users", data)
		Object.assign(user, data)
		delete user.token
		delete user.password
		return user
	}
	
	async unbindWX() {
		await dbHelper.update("uni-id-users", {
			_id: this.ctx.auth.uid,
			nickname: '',
			avatar: '',
			merchant_info: {
				wx_unionid: '',
				wx_openid: {
					"mp-weixin": ''
				}
			}
		})
		return await dbHelper.getById("uni-id-users", this.ctx.auth.uid)
	}
}
